<div id="fb-root"></div>
<script type="text/javascript" src="http://connect.facebook.net/en_US/all.js"></script>
<script type="text/javascript">
FB.init({
appId : '271211432894561',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse XFBML
oauth : false // disable OAuth since we're not ready for it
});
</script>

<?php
	session_start();
	require_once 'php-sdk/facebook.php' ;
	require_once 'php-sdk/base_facebook.php' ;
	$free_slots['Supervisor'] = 1;
	$free_slots['Office worker'] = 2;
	$free_slots['Production line worker'] = 4;
	
	connect_db();
	
	$func=isset($_GET['func'])?$_GET['func']:'';
	if(function_exists($func)) 
	{
		$func($_GET);
	}
	
	
	/*function initialize() {

		$conn = connect_db();
		if (!isset($_SESSION['facebook']))
		{
			$facebook = connect_fb();
			$_SESSION['facebook'] = $facebook;
		}
		
		if (!isset($_SESSION['user_id']))
		{
			$user = facebook_api_call("/me") ;
			$_SESSION['user_id'] = $user['id'];
		}
		
		if (!isset($_SESSION['factory_id']))
		{
			$factory_id = get_factory_id($user['id']);
			$_SESSION['factory_id'] = $factory_id;
		}
		
	}*/
	
	function get_user_id() {
		$user = facebook_api_call('/me?fields=id');
		return $user['id'];
	}
	
	/*
	function set_user_id($string) {
		$GLOBALS['$user_id'] = $string;
	}
	*/
	function connect_fb () {
		$fb_app_id = '271211432894561';
		$fb_secret = 'ac4575f2817581409a43994a60c4c0bc';
		$canvas_page = 'https://apps.facebook.com/frenfactory/';

		$facebook = new Facebook(array(
			'appId' => $fb_app_id,
			'secret' => $fb_secret,
		));

		if (isset($_POST['signed_request']))
		{
			$signed_request = $_POST['signed_request'];
			$_SESSION['signed_request'] = $signed_request;
		}
		else if (isset($_SESSION['signed_request']))
		{
			$signed_request = $_SESSION['signed_request'];
		}
		list($encoded_sig, $payload) = explode('.', $signed_request, 2); 
		$data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);

		if (empty($data["user_id"])) {
			// If the user id is not present, redirect the user to the 
			// page to allow the application access to his data
		
			// Permissions that the application requires
			$fb_perms_required = "friends_photos, friends_status, publish_stream, read_stream"; // Include all the permissions you want, 
								 // separated by commas
			$auth_url = "http://www.facebook.com/dialog/oauth?client_id=" 
						. $fb_app_id . "&redirect_uri=" . urlencode($canvas_page)
						. "&scope=" . $fb_perms_required;

			// send a script tag to
			echo "<script> top.location.href='" . $auth_url . "'</script>";
			
			// Stop script execution. Any code below exit() will not be executed.
			exit();
		}
			
		return $facebook;
	}
	
	function facebook_api_call($string)
	{
		$facebook = connect_fb();
		$result = $facebook->api($string);
		return $result;
	}
	
	function connect_db () {
		$conn = mysql_connect ("localhost","root","password") ;
		if (!$conn) {
			die ('Could not connect: ' . mysql_error()) ; 
		}
		mysql_select_db ("frenfactory",$conn);
		return $conn ;
	}
	
	function get_factory_id ($user_id) {
		$query = "SELECT factory_id FROM User WHERE user_id = " . $user_id;
		$result = mysql_query($query);
		if (!$result)
			echo "Error querying database: ". mysql_error();
		// If the user is old user, retrieve his factory id
		if ($row = mysql_fetch_array($result)) 
			return $row["factory_id"];
		// If the user is new user, create a new factory id for him
		else {
			add_factory_id ($user_id) ;
		}
	}
	
	function add_factory_id ($user_id) {
		if ($user_id == "")
			return ;
		$query = "INSERT INTO User(user_id,credit) VALUES ('$user_id',1000)" ;
		if (!mysql_query($query)) {
			die('Error: ' . mysql_error());
		}
		$factory_id = get_factory_id ($user_id) ;
		$query = "SELECT job_title_id,num_of_slots FROM Job_title" ;
		$job_title = mysql_query($query) ;
		if (!$job_title)
			echo "Error querying database: ". mysql_error() ;
		while ($row = mysql_fetch_array($job_title)) {
			$query = "INSERT INTO Job_title_progress VALUES ('$factory_id'," . $row["job_title_id"] . "," . $row["num_of_slots"] . ",0,0,0)" ;
			if (!mysql_query($query)) {
				die('Error: ' . mysql_error());
			}
		}		
		return  $factory_id ;
	}	
	
	function get_progress ($factory_id, $job_title_id) {
		$query = "SELECT curr_progress FROM Job_title_progress 
					WHERE factory_id = '$factory_id' 
					AND job_title_id = '$job_title_id'" ;
		$result = mysql_query ($query) ;
		if (!$result)
			echo "Error querying database: ". mysql_error();
		if ($row = mysql_fetch_array($result)) 
			return $row["curr_progress"] ;
		return -1 ;
	}
	
	function get_progress_last ($factory_id, $job_title_id) {
		$query = "SELECT last_progress FROM Job_title_progress 
					WHERE factory_id = '$factory_id' 
					AND job_title_id = '$job_title_id'" ;
		$result = mysql_query ($query) ;
		if (!$result)
			echo "Error querying database: ". mysql_error();
		if ($row = mysql_fetch_array($result)) 
			return $row["last_progress"] ;
		return -1 ;
	}
	
	function get_progress_curr ($factory_id, $job_title_id) {
		$query = "SELECT curr_progress FROM Job_title_progress 
					WHERE factory_id = '$factory_id' 
					AND job_title = '$job_title_id'" ;
		$result = mysql_query ($query) ;
		if (!$result)
			echo "Error querying database: ". mysql_error();
		if ($row = mysql_fetch_array($result)) 
			return $row["curr_progress"] ;
		return -1 ;
	}
	
	function get_progress_max ($job_title_id) {
		$query = "SELECT max_exp FROM Job_title
					WHERE job_title_id = '$job_title_id'" ;
		$result = mysql_query ($query) ;
		if (!$result)
			echo "Error querying database: ". mysql_error();
		if ($row = mysql_fetch_array($result))
			return $row["max_exp"] ;
		return -1 ;
	}
	
	function get_employee ($factory_id,$job_title,$job_position) {
		$query = "SELECT worker_id FROM Factory 
					WHERE factory_id = '$factory_id' AND
						job_title_id = '$job_title' AND
						job_position = '$job_position'" ;
		$result = mysql_query ($query) ;
		if (!$result)
			echo "Error querying database: ". mysql_error();
		if ($row = mysql_fetch_array($result))
			return $row["worker_id"] ;
		return -1 ;				
	}
	
	/*function get_certain_workers($factory_id, $type)
	{
		global $num_of_workers ;
		global $free_slots ;
		$worker = array($num_of_workers[$type]) ;
		for ($i=0; $i<$num_of_workers[$type]; $i++)
			$worker[$i]=-1 ;
		
		$query = "SELECT job_title_id FROM Job_title WHERE job_name = '".$type."'" ;
		$title_id_array = mysql_fetch_array(mysql_query($query)) ;
		$title_id = $title_id_array["job_title_id"] ;
		
		$query = "SELECT worker_id, job_position FROM Factory WHERE job_title = ".$title_id." AND factory_id = ".$factory_id ;
		$result = mysql_query($query) ;
		if (!$result)
			echo "Error querying database: ".mysql_error() ;
		while ($row = mysql_fetch_object($result))
		{
			$free_slots[$type]-- ;
			$worker[$row->job_position] = $row->worker_id ;
		}
		return $worker ;
	}*/
	
	function get_certain_workers($factory_id, $type)
	{
		global $free_slots;
		
		$sql = "SELECT job_title_id, num_of_slots FROM Job_title WHERE job_name = '".$type."'";
		$title_id_array = mysql_fetch_array(mysql_query($sql));
		$title_id = $title_id_array["job_title_id"];
		
		$worker = array($title_id_array["num_of_slots"]);
		for ($i=0;$i<$title_id_array["num_of_slots"];$i++)
		{
			$worker[$i]=-1;
		}
		
		$sql = "SELECT worker_id, job_position FROM Factory WHERE job_title_id = ".$title_id." AND factory_id = ".$factory_id;
		$result = mysql_query($sql);
		if (!$result)
			echo "Error querying database: ".mysql_error();
		while ($row = mysql_fetch_object($result))
		{
			$free_slots[$type]--;
			$worker[$row->job_position] = $row->worker_id;
		}
		return $worker;
	}
	
	function get_certain_workers_json($factory_id, $type)
	{
		global $free_slots;
		
		$sql = "SELECT job_title_id, num_of_slots FROM Job_title WHERE job_name = '".$type."'";
		$title_id_array = mysql_fetch_array(mysql_query($sql));
		$title_id = $title_id_array["job_title_id"];
		
		$worker = array($title_id_array["num_of_slots"]);
		for ($i=0;$i<$title_id_array["num_of_slots"];$i++)
		{
			$worker[$i]=-1;
		}
		
		$sql = "SELECT worker_id, job_position FROM Factory WHERE job_title_id = ".$title_id." AND factory_id = ".$factory_id;
		$result = mysql_query($sql);
		if (!$result)
			echo "Error querying database: ".mysql_error();
		while ($row = mysql_fetch_object($result))
		{
			$free_slots[$type]--;
			$worker[$row->job_position] = $row->worker_id;
		}
		return json_encode($worker);
	}
	
	function get_friend_list($stuff)
	{
		
		$user_id = $stuff['user_id'];
		$search = isset($stuff['q'])?$stuff['q']:' ';
		$friendlistquery = "SELECT uid, name, profile_url FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = ".$user_id.") AND strpos(lower(name), '".$search."') >= 0 ORDER BY name ASC";

		$friendlist = facebook_api_call(array(
							'method'=>'fql.query',
							'query'=>$friendlistquery,
							));
		return json_encode($friendlist);
	}
	
	function get_all_user_ids()
	{
		$query_string = "SELECT user_id FROM User";
		$result = mysql_query($query_string);
		if (! $result)
		{
			echo "Error database query @get_all_user_ids : " . mysql_error();
		}
		$return = array();
		while ($row = mysql_fetch_array($result))
		{
			array_push($return, $row["user_id"]);
		}
		return $return;
	}
	
// UPDATE FUNCTION ---------------------------------------------------------------------------
// update Factory table
function update_Factory_table($column, $value, $factory_id, $worker_id)
{
	$query_string = "UPDATE Factory SET " . $column . " = " . $value . " WHERE factory_id = " . $factory_id . " AND worker_id = " . $worker_id;
	if (! mysql_query($query_string))
	{
		echo "Error updating database @ update_Factory_table : " . mysql_error();
	}
	else
		return;
}

// update Job_title_progress table
function update_Job_title_progress_table($column, $value, $factory_id, $job_title_id)
{
	$query_string = "UPDATE Job_title_progress SET " . $column . " = " . $value . " WHERE factory_id = " . $factory_id . " AND job_title_id = " . $job_title_id;
	if (! mysql_query($query_string))
	{
		echo "Error updating database @ update_Job_title_progress_table : " . mysql_error();
	}
}

// update User table
function update_User_table($column, $value, $user_id)
{
	$query_string = "UPDATE User SET " . $column . " = " . $value . " WHERE user_id = " . $user_id;
	if (! mysql_query($query_string))
	{
		echo "Error updating database @ update_User_table : " . mysql_error();
	}
}
// END UPDATE FUNTCION -----------------------------------------------------------------------------------

// SELECT FUNCTION ---------------------------------------------------------------------------------------
function get_efficiency($factory_id, $worker_id)
{
	$query_string = "SELECT efficiency FROM Factory WHERE factory_id = " . $factory_id . " AND worker_id = " . $worker_id;
	$result = mysql_query($query_string);
	if (! $result)
	{
		echo "Error querying database @get_efficiency : " . mysql_error();
	}
	$row = mysql_fetch_array($result);
	return $row["efficiency"] + 1;
}

// select from User table ----------------------------------------------------
function get_from_Use_table($column, $user_id)
{
	$query_string = "SELECT " . $column . " FROM User WHERE user_id = " . $user_id;
	$result = mysql_query($query_string);
	if (! $result)
	{
		echo "Error database query @ get_from_Use_table @ " . $column . " : " . mysql.error();
	}
	$row = mysql_fetch_array($result);
	return $row[$column];

}

function get_my_factory_id($user_id)
{
	return get_from_Use_table('factory_id', $user_id);
}

function get_credit($user_id)
{
	return get_from_Use_table('credit', $user_id);
}

// return an array of job title ids
function get_job_title_id_list()
{
	$query_string = "SELECT job_title_id FROM Job_title";
	$result = mysql_query($query_string);
	if (! $result)
	{
		echo "Error database query @ get_job_title_id_list : " . mysql.error();
	}
	$list = array();
	while ($row = mysql_fetch_array($result))
	{
		array_push($list, $row["job_title_id"]);
	}
	return $list;
}

// return an array of worker ids
function get_worker_id_list($factory_id, $job_title_id)
{
	$query_string = "SELECT worker_id FROM Factory WHERE factory_id = " . $factory_id . " AND job_title_id = " . $job_title_id;
	$result = mysql_query($query_string);
	if (! $result)
	{
		echo "Error database query @ get_worker_id_list : " . mysql.error();
	}
	$list = array();
	while ($row = mysql_fetch_array($result))
	{
		array_push($list, $row["worker_id"]);
	}
	return $list;
}

function get_new_total_num($worker_id, $job_title_id)
{
	$new_total_num = 0;
	switch ($job_title_id)
	{
		case 1 : $new_total_num = get_num_of_photos($worker_id); break;
		case 2 : $new_total_num = get_num_of_posts($worker_id); break;
		case 3 : $new_total_num = get_num_of_statuses($worker_id); break;
		default : echo "No such job" . $job_title_id;
	}
	return $new_total_num;
}

function get_total_num($factory_id, $worker_id)
{
	$query_string = "SELECT total_num FROM Factory WHERE factory_id = " . $factory_id . " AND worker_id = " . $worker_id;
	$result = mysql_query($query_string);
	if (! $result)
	{
		echo "Error database query @ get_total_num : " . mysql.error();
	}
	$row = mysql_fetch_array($result);
	return $row["total_num"];
}

// select from Job_title_progress table ----------------------------------------
function get_from_Job_title_progress_table($column, $factory_id, $job_title_id)
{
	$query_string = "SELECT " . $column . " FROM Job_title_progress WHERE factory_id = " . $factory_id . " AND job_title_id = " . $job_title_id;
	$result = mysql_query($query_string);
	if (! $result)
	{
		echo "Error database query @ get_from_Job_title_progress_table @ " . $column . " : " . mysql.error();
	}
	$row = mysql_fetch_array($result);
	return $row[$column];
}

function get_curr_progress($factory_id, $job_title_id)
{
	return get_from_Job_title_progress_table('curr_progress', $factory_id, $job_title_id);
}

function get_last_progress($factory_id, $job_title_id)
{
	return get_from_Job_title_progress_table('last_progress', $factory_id, $job_title_id);
}

function get_level_id($factory_id, $job_title_id)
{
	return get_from_Job_title_progress_table('level_id', $factory_id, $job_title_id);
}

function get_extra_credits($factory_id, $job_title_id)
{
	return get_from_Job_title_progress_table('extra_credits', $factory_id, $job_title_id);
}
// select from Level table ----------------------------------------------------
function get_from_Level_table($column, $level_id, $job_title_id)
{
	$query_string = "SELECT " . $column . " FROM Level WHERE level_id = " . $level_id . " AND job_title_id = " . $job_title_id;
	$result = mysql_query($query_string);
	if (! $result)
	{
		echo "Error database query @ get_from_Level_table @ " . $column . " : " . mysql.error();
	}
	$row = mysql_fetch_array($result);
	return $row[$column];
}

function get_max_exp($level_id, $job_title_id)
{
	return get_from_Level_table('max_exp', $level_id, $job_title_id);
}

function get_credit_earned($level_id, $job_title_id)
{
	return get_from_Level_table('credit_earned', $level_id, $job_title_id);
}

function get_level_up($curr_progress, $level_id, $job_title_id)
{
	$tmp_curr_progress = $curr_progress;
	$tmp_credit_earned = 0;
	
	$query_string = "SELECT * FROM Level WHERE level_id >= " . $level_id . " AND job_title_id = " . $job_title_id;
	$result = mysql_query($query_string);
	if (! $result)
	{
		echo "Error database query @get_level_up : " . mysql_error();
	}
	
	while ($row = mysql_fetch_array($result))
	{
		$tmp_curr_progress -= $row["max_exp"];
		if ($tmp_curr_progress >= 0) {
			$tmp_credit_earned += $row["credit_earned"];
		}
		else
		{
			$tmp_curr_progress += $row["max_exp"];
			$level_id = $row["level_id"]--;
			return array("curr_progress"=>$tmp_curr_progress, "credit_earned"=>$tmp_credit_earned, "level_id"=>$level_id);
		}
	}
	
	die("Not enough levels");
	
}

// END SELECT FUNCTION ----------------------------------------------------------------------------------

function update_progress($user_id)
{
	$factory_id = get_my_factory_id($user_id);
	$credit = get_credit($user_id);
	
	$job_title_id_list = get_job_title_id_list();
	
	// loop 1 ------------------------------------------------------------------------------------------
	// for each job type
	for ($i = 0; $i < count($job_title_id_list); $i++)
	{
		$job_title_id = $job_title_id_list[$i];
		$worker_id_list = get_worker_id_list($factory_id, $job_title_id);
		
		// loop 2 --------------------------------------------------------------------------------------
		// for each worker
		for ($j = 0; $j < count($worker_id_list); $j++)
		{
			$worker_id = $worker_id_list[$j];
			
			// CALCULATE UPDATES -------------------------------------------------------------------------
			$new_total_num = get_new_total_num($worker_id, $job_title_id);
			$total_num = get_total_num($factory_id, $worker_id);
			
			$num_of_updates = ($new_total_num > $total_num) ? ($new_total_num - $total_num) : 0;
			$efficiency = get_efficiency($factory_id, $worker_id);
			$num_of_updates *= $efficiency;
			
			// update num_of_updates, total_num
			update_Factory_table('num_of_updates', $num_of_updates, $factory_id, $worker_id);
			update_Factory_table('total_num', $new_total_num, $factory_id, $worker_id);
			// END CALCULTATING UPDATES ------------------------------------------------------------------
			
			// PROGRESS ----------------------------------------------------------------------------------
			$curr_progress = get_curr_progress($factory_id, $job_title_id);
			$last_progress = get_last_progress($factory_id, $job_title_id);
			// update last_progress
			update_Job_title_progress_table('last_progress', $curr_progress, $factory_id, $job_title_id);
						
			// if there are updates
			if ($num_of_updates > 0)
			{
				$curr_progress += $num_of_updates;
				$level_id = get_level_id($factory_id, $job_title_id);
				$max_exp = get_max_exp($level_id, $job_title_id);
				if ($curr_progress >= $max_exp)
				{
				
					$result = get_level_up($curr_progress, $level_id, $job_title_id);
					
					$curr_progress = $result["curr_progress"];
					$level_id = $result["level_id"];
					$credit_earned = $result["credit_earned"];
					
					/*
					// progress bar full, reset progress bar and increase level by one
					$curr_progress = 0;
					$credit_earned = get_credit_earned($level_id, $job_title_id);
					$level_id++;
					*/
					
					$extra_credits = get_extra_credits($factory_id, $job_title_id);
					$credit += $credit_earned + $extra_credits;
					
					// update level_id
					update_Job_title_progress_table('level_id', $level_id, $factory_id, $job_title_id);
					
				}
			}
			// update curr_progress if there are updates
			update_Job_title_progress_table('curr_progress', $curr_progress, $factory_id, $job_title_id);
			// END PROGRESS ------------------------------------------------------------------------------
		}
		// END loop 2 ----------------------------------------------------------------------------------
	}
	// END loop 1 --------------------------------------------------------------------------------------
	
	// update credit
	update_User_table('credit', $credit, $user_id);
	
	check_achievement($user_id);
}
	
	// return current total number of photos of $user_id
	function get_num_of_photos($user_id)
	{
		$query_string = "SELECT pid FROM photo WHERE aid IN (SELECT aid FROM album WHERE owner = " . $user_id . ")";
    
		//echo $query_string . "<br />";
    
		$photolist = facebook_api_call(array('method' => 'fql.query', 'query' => $query_string));
    
		//var_dump($photolist);
		//echo "<br />";
    
		return count($photolist);
	}
	
	// return current total number of statuses of $user_id
	function get_num_of_statuses($user_id)
	{
		$query = "SELECT uid FROM status WHERE uid = " . $user_id;
    
		// echo $query . "<br />";
    
		$statuslist = facebook_api_call(array('method'=>'fql.query', 'query'=>$query));
    
		// var_dump($statuslist);
		// echo "<br />";
    
		return count($statuslist);
	}
	
	// return current total number of posts of $user_id
	function get_num_of_posts($user_id)
	{
		$query = "SELECT post_id FROM stream WHERE source_id = " . $user_id;
    
		// echo $query . "<br />";
    
		$postlist = facebook_api_call(array('method'=>'fql.query', 'query'=>$query));
    
		// var_dump($postlist);
		// echo "<br />";
    
		return count($postlist);
	}
	
	// return current total number of tags of $user_id
	function get_num_of_tags($user_id)
	{
		$query = "/" . $user_id . "/tags";
    
		//echo $query . "<br />";
    
		$taglist = facebook_api_call($query);
    
		// var_dump($taglist);
		// echo "<br />";
    
		return count($taglist["data"]);
	}

	// return current total number of checkins of $user_id
	function get_num_of_checkins($user_id)
	{
		$query = "/" . $user_id . "/checkins";
    
		//echo $query . "<br />";
    
		$checkinlist = facebook_api_call($query);
    
		// var_dump($checkinlist);
		// echo "<br />";
    
		return count($checkinlist["data"]);
	}
	
// Factory API ---------------------------------------------------------------------
	function get_certain_items($factory_id, $job_title_id)
	{
		$query_string = "SELECT item_id FROM Item_list 
							WHERE job_title_id = " . $job_title_id . " 
								AND item_id IN 
									(SELECT item_id FROM Item WHERE factory_id = " . $factory_id . " ) ";
		$result = mysql_query($query_string);
		if (! $result)
		{
			echo "Error database query @get_certain_items : " . mysql_error();
		}
		
		$return = array();
		while ($row = mysql_fetch_array($result))
		{
			array_push($return, $row["item_id"]);
		}
		
		return $return;
	}
	
	function get_certain_item_quantity($factory_id, $job_title_id)
	{
		$query_string = "SELECT item_id, quantity FROM Item 
							WHERE factory_id = " . $factory_id . "
								AND item_id IN 
									(SELECT item_id FROM Item_list WHERE job_title_id = " . $job_title_id . " ) ";
		$result = mysql_query($query_string);
		if (! $result)
		{
			echo "Error database query @get_certain_items : " . mysql_error();
		}
		
		$return = array();
		while ($row = mysql_fetch_array($result))
		{
			$return[$row["item_id"]] = $row["quantity"];
		}
		
		return $return;		
	}
	
	function get_item_quantity_by_id($factory_id, $item_id)
	{
		$query_string = "SELECT quantity FROM Item WHERE factory_id = " . $factory_id . " AND item_id = " . $item_id;
		$result = mysql_query($query_string);
		if (! $result)
		{
			echo "Error database query @get_item_quantity_by_id : " . mysql_error();
		}
		$row = mysql_fetch_array($result);
		return $row["quantity"];
	}
	
	function translateItemName($item_id)
	{
		switch ($item_id)
		{
			case 1: return "Big Deal_icon.png";
			case 2: return "Golf Set_icon.png";
			case 3: return "A.C.C.A Training_icon.png";
			case 4: return "Cabinet_icon.png";
			case 5: return "A.C.T.A Training_icon.png";
			case 6: return "Toolbox_icon.png";
			default: die("No item matched : " . $item_id);
		}
	}
// -------------------------------------------------------------------------------------------

// Welcome API -------------------------------------------------------------------------------
	function add_new_user($user_id)
	{
		add_into_User($user_id);
		
		$factory_id = get_my_factory_id($user_id);
		
		add_into_Item($factory_id);
		
		add_into_Job_title_progress($factory_id);
	}
	
	function add_into_User($user_id)
	{
		$query_string = "INSERT INTO User(user_id,credit) VALUES ('$user_id',1000)";
		if (! mysql_query($query_string)) 
		{
			die("Error inserting into database @add_into_User" . mysql_error());
		}
	}
	
	function add_into_Item($factory_id)
	{
		$query_string = "SELECT item_id FROM Item_list";
		$result = mysql_query($query_string);
		if (! $result)
		{
			die("Error inserting into database @add_into_Item" . mysql_error());
		}
		while ($row = mysql_fetch_array($result))
		{
			$item_id = $row["item_id"];
			$query_string = "INSERT INTO Item (factory_id, item_id) VALUE ('$factory_id', '$item_id')";
			if (! mysql_query($query_string)) 
			{
				die("Error inserting into database @add_into_Item" . mysql_error());
			}
		}
	}
	
	function add_into_Job_title_progress($factory_id)
	{
		$query_string = "SELECT job_title_id, num_of_slots FROM Job_title";
		$result = mysql_query($query_string);
		if (! $result)
		{
			die("Error inserting into database @add_into_Job_title_progress" . mysql_error());
		}
		while ($row = mysql_fetch_array($result))
		{
			$job_title_id = $row["job_title_id"];
			$num_of_slots = $row["num_of_slots"];
			$query_string = "INSERT INTO Job_title_progress (factory_id, job_title_id, num_of_slots) VALUE ('$factory_id', '$job_title_id', '$num_of_slots')";
			if (! mysql_query($query_string)) 
			{
				die("Error inserting into database @add_into_Item" . mysql_error());
			}
		}
	}
//------------------------------------------------------------------------------------------------
	
// Achievement API-------------------------------------------------------------------------------
	function check_achievement($user_id)
	{
		$factory_id = get_factory_id($user_id);
		$job_title_ids = get_job_title_id_list();
		for ($i = 0; $i < count($job_title_ids); $i++)
		{	
			$job_title_id = $job_title_ids[$i];
			$level_id = get_level_id($factory_id, $job_title_id);
			$query_string = "SELECT achievement_id, description FROM Achievement_list 
								WHERE job_title_id = " . $job_title_id . " AND level_id <= " . $level_id . "
									AND achievement_id NOT IN (SELECT achievement_id FROM Achievement WHERE user_id = " . $user_id . ")";
			$result = mysql_query($query_string);
			if (! $result)
			{
				die("Error querying database @check_achievement : " . mysql_error());
			}
			while ($row = mysql_fetch_array($result))
			{
				insert_achievement_table($user_id, $row["achievement_id"]);
				post_achievement($user_id, $row["description"]);
			}
		}
	}
	
	function insert_achievement_table($user_id, $achievement_id)
	{
		$query_string = "INSERT INTO Achievement(user_id, achievement_id) VALUES (". $user_id . " , " . $achievement_id . ")";
		mysql_query($query_string);
	}
	
	function post_achievement($user_id, $msg)
	{
				echo "<div id=\"fb-root\"></div>
							<script type=\"text/javascript\" src=\"http://connect.facebook.net/en_US/all.js\"></script>
							<script type=\"text/javascript\">
							FB.init({
							appId : '271211432894561',
							status : true, // check login status
							cookie : true, // enable cookies to allow the server to access the session
							xfbml : true, // parse XFBML
							oauth : false // disable OAuth since we're not ready for it
							});

							FB.ui(
							{
							method: 'feed',
							name: '".$msg."',
							link: 'apps.facebook.com/frenfactory',
							picture: 'http://107.20.229.155/frenfactory/images/frenfactory_icon.png',
							caption: 'Help your friend out by uploading photos!',
							description: 'Unwilling to stay as a worker? Play FrenFactory and run your own factory!',
							to: '".$user_id."'
							},
							function(response) {
							if (response && response.post_id) {
								window.location.href='play.php';
							} else {
								window.location.href='play.php';
								}
							}
							);
							</script>";
//window.location.href='play.php';
	}

//-------------------------------------------------------------------------------------------------
	function insert_friends_into_factory($staff)
	{
		global $free_positions;
		$factory_id = '';

		$zero = 0;
		foreach($staff as $key => $value)
		{
			if ($key != "func")
			{
				if ($key == "factory_id")
				{
					$factory_id = $value;
					continue;
				}
				else
				{
					if ($value == "supervisor")
						$type = "Supervisor";
					if ($value == "production")
						$type = "Production line worker";
					if ($value == "office")
						$type = "Office worker";
				
					//find job id
					$sql = "SELECT job_title_id, num_of_slots, fb_action FROM Job_title WHERE job_name = '".$type."'";
					$id = mysql_fetch_assoc(mysql_query($sql));
			
					
					//really dumb way of finding the next free position to insert
					for ($i=0;$i<$id["num_of_slots"];$i++)
					{
						$sql = "SELECT * FROM Factory WHERE factory_id=".$factory_id." AND job_title_id=".$id["job_title_id"]." AND job_position=".$i;
						$result = mysql_query($sql);
						if ( $result ) {
							if ( mysql_num_rows($result) == 0 ) {
								break;
							}
						}
					}
					//insert query
					$sql = "INSERT INTO Factory (factory_id, job_title_id, job_position, worker_id, efficiency, total_num, num_of_updates) VALUES (".$factory_id.",".$id["job_title_id"].",".$i.",".$key.",0,0,0)";
					$result = mysql_query($sql);
					if (!$result)
					{
						echo "Error querying database: ". mysql_error();
					}
					else
					{
						if ($id["job_title_id"]==1)
						{
							$total_num = get_num_of_photos($key);
						}
						else if ($id["job_title_id"]==2)
						{
							$total_num = get_num_of_posts($key);
						}
						else if ($id["job_title_id"]==3)
						{
							$total_num = get_num_of_statuses($key);
						}
						update_Factory_table('total_num',$total_num, $factory_id, $key);
						
						if ($id["job_title_id"] == 1)
						{
							echo "<div id=\"fb-root\"></div>
							<script type=\"text/javascript\" src=\"http://connect.facebook.net/en_US/all.js\"></script>
							<script type=\"text/javascript\">
							FB.init({
							appId : '271211432894561',
							status : true, // check login status
							cookie : true, // enable cookies to allow the server to access the session
							xfbml : true, // parse XFBML
							oauth : false // disable OAuth since we're not ready for it
							});

							FB.ui(
							{
							method: 'feed',
							name: 'has hired you to be Da Boss!',
							link: 'apps.facebook.com/frenfactory',
							picture: 'http://107.20.229.155/frenfactory/images/frenfactory_icon.png',
							caption: 'Help your friend out by uploading photos!',
							description: 'Unwilling to stay as a worker? Play FrenFactory and run your own factory!',
							to: '".$key."'
							},
							function(response) {
							if (response && response.post_id) {
								window.location.href='play.php';
							} else {
								window.location.href='play.php';
								}
							}
							);
							</script>";
						}
						else
							header("Location:http://107.20.229.155/frenfactory/play.php");
							
					}
				}
			}
		}
	}
	
	function remove_friend_from_factory($staff)
	{
		// $staff is an array: Array ( [func] => remove_friend_from_factory [factory_id] => 2 [worker_id] => 715317954 )
		global $free_slots;
		$factory_id = '';
		$worker_id = '';
		foreach($staff as $key => $value)
		{
			if ($key != "func") //ignore func
			{
				if ($key == "factory_id") //map factory_id
				{
					$factory_id = $value;
					continue;
				}
				if ($key == "worker_id") //map worker_id
				{
					$worker_id = $value;
				}
				//delete worker from factory
				$sql = "SELECT job_name FROM Job_title AS t JOIN Factory AS f ON t.job_title_id = f.job_title_id WHERE factory_id = ".$factory_id." AND worker_id = ".$worker_id;
				$job_title =  mysql_fetch_assoc(mysql_query($sql));
				
				$sql = "DELETE FROM Factory WHERE factory_id = ".$factory_id." AND worker_id = ".$worker_id;
	
				$result = mysql_query($sql);
				if (!$result)
					echo "Error querying database: ". mysql_error();
				else
					$free_slots[$job_title["job_name"]]++;
			}
		}

	}
	// Get job title id 
	function get_job_title_id ($job_name) {
		$query = "SELECT job_title_id FROM Job_title WHERE job_name = '$job_name'";
		$job_title_id_array = mysql_fetch_array(mysql_query($query));
		return $job_title_id_array["job_title_id"];
	}
	
	// Get item list
	function get_items($job_name) {
		$counter = -1;
		$job_title_id = get_job_title_id ($job_name) ;		
		
		$query = "SELECT item_id,item_name,cost FROM Item_list WHERE job_title_id = '$job_title_id'" ;
		$result = mysql_query($query);
		if (!$result)
			echo "Error querying database: " . mysql_error() ;
		while ($row = mysql_fetch_array($result)) {
			$counter += 1 ;  
			$items[$counter]["item_id"] = $row["item_id"] ;
			$items[$counter]["item_name"] = $row["item_name"] ;
			$items[$counter]["cost"] = $row["cost"] ;
		}
		return $items;
	}

	// Buy item ;
	function buy_item ($stuff) {
		$factory_id ;
		$item_id ;
		$credit ;
		$job_title_id ;
		$quantity ;
		// $stuff is an array: Array ( [func] => buy_item [factory_id]  [item_id] [credit] [job_title_id] [quantity] )
		foreach($stuff as $key => $value) {
			if ($key == "factory_id")
				$factory_id = $value ;
			if ($key == "item_id")
				$item_id = $value ;
			if ($key == "credit")
				$credit = $value ;
			if ($key == "job_title_id")
				$job_title_id = $value ; 
			if ($key == "quantity")
				$quantity = $value ;
		}
		update_credit ($factory_id,$credit) ;
		update_item ($factory_id,$item_id) ;
		update_item_effect ($factory_id,$job_title_id,$item_id,$quantity) ;
		header("Location:http://107.20.229.155/frenfactory/buy.php");
	}
	
	// Update the total credit of the factory
	function update_credit ($factory_id,$credit) {
		$query = "UPDATE User SET credit = '$credit' WHERE factory_id = '$factory_id'" ;
		$result = mysql_query($query) ;
		if (!$result)
			echo "Error querying databas: " . mysql_error() ;
	}
	
	// Update the new item in the factory
	function update_item ($factory_id,$item_id) {
		$query = "UPDATE Item SET quantity = quantity+1 WHERE factory_id = '$factory_id' AND item_id = '$item_id'" ;
		$result = mysql_query($query) ;
		if (!$result)
			echo "Error querying databas: " . mysql_error() ;
	}
	
	// Update the item effect
	function update_item_effect ($factory_id,$job_title_id,$item_id,$position) {
		$bonus = get_item_bonus ($item_id) ;
		switch ($item_id) {
			case 1:
			case 3:
			case 5:
				$query = "UPDATE Factory SET efficiency = efficiency + '$bonus' WHERE factory_id = '$factory_id' AND job_title_id = '$job_title_id' AND job_position = '$position' " ;
				break ;
			case 2:
			case 4:
			case 6:
				$query = "UPDATE Job_title_progress SET extra_credits = extra_credits + '$bonus' WHERE factory_id = '$factory_id' AND job_title_id = '$job_title_id' " ;
				break ;
		}
		$result = mysql_query($query) ;
		if (!$result)
			echo "Error querying databas: " . mysql_error() ;
	}
	// Get number of slots for a job title in a factory
	function get_job_title_num_of_slots ($factory_id,$job_name) {
		$job_title_id = get_job_title_id ($job_name) ;
		$query = "SELECT num_of_slots FROM Job_title_progress WHERE factory_id = '$factory_id' AND job_title_id = '$job_title_id' " ;
		$result = mysql_fetch_array(mysql_query($query));
		return $result["num_of_slots"];
	}
	
	// Get number of supersivor slots in a factory
	function get_supervisor_num_of_slots ($factory_id) {
		return get_job_title_num_of_slots ($factory_id,"Supervisor") ;
	}
	// Get number of office worker slots in a factory
	function get_office_worker_num_of_slots ($factory_id) {
		return get_job_title_num_of_slots ($factory_id,"Office worker") ;
	}
	// Get number of production line worker slots in a factory
	function get_production_worker_num_of_slots ($factory_id) {
		return get_job_title_num_of_slots ($factory_id,"Production line worker") ;
	}
	
	// Get item quantity
	function get_item_quantity ($factory_id,$item_id) {
		$query = "SELECT quantity FROM Item WHERE factory_id = '$factory_id' AND item_id = '$item_id'" ;
		$result = mysql_fetch_array(mysql_query($query));
		return $result["quantity"];
	}
	
	// Get item effect bonus
	function get_item_bonus ($item_id) {
		$query = "SELECT bonus FROM Item_list WHERE item_id = '$item_id' " ;
		$result = mysql_fetch_array(mysql_query($query));
		return $result["bonus"];
	}
?>